<template>
  <div class="exportExcel-container">
    <el-button
      type="primary"
      icon="el-icon-download"
      :size="size"
      @click="handleExportExcel"
    >导出</el-button>
  </div>
</template>

<script>
const ExportJsonExcel = require('js-export-excel')

export default {
  name: 'ExportExcel',
  props: {
    size: {
      type: String,
      default: null
    },
    sheetData: {
      type: Array,
      required: true
    },
    fileName: {
      type: String,
      default: '表格'
    },
    sheetFilter: {
      type: Array,
      default: null
    },
    sheetHeader: {
      type: Array,
      default: null
    },
    pctArrKeys: { // 需要处理百分比的数据
      type: Array,
      default: null
    }

  },
  methods: {
    handleExportExcel() {
      const option = {
        fileName: this.fileName + (new Date()).getTime()
      }
      const sheetData = this.formatData(this.sheetData)
      option.datas = [
        {
          sheetData,
          sheetName: '表格', // Excel文件sheel名称
          sheetFilter: this.sheetFilter ? this.sheetFilter : Object.keys(this.sheetData[0]),
          sheetHeader: this.sheetHeader ? this.sheetHeader : Object.keys(this.sheetData[0]),
          columnWidths: this.sheetHeader ? this.sheetHeader.map(() => 10) : Object.keys(this.sheetData[0]).map(() => 10)
        }
      ]
      const toExcel = new ExportJsonExcel(option)
      toExcel.saveExcel()
    },
    formatData(data) {
      if (!data && !data.length) return
      const newData = JSON.parse(JSON.stringify(data))
      for (const o of newData) {
        if (this.pctArrKeys && this.pctArrKeys.length > 0) {
          this.pctArrKeys.map(itemKey => {
            o[itemKey] = `${(o[itemKey] * 100).toFixed(2)}%`
          })
        }
      }
      return newData
    }
  }
}
</script>

<style scoped></style>
